package com.qst.yunpan.controller;

import com.qst.yunpan.pojo.User;
import com.qst.yunpan.service.FileService;
import com.qst.yunpan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FileService fileService;

    @RequestMapping("/login")
    public String login(HttpServletRequest request, User user) {
        // 判断输入是否合法
        if (user.getUsername() == null ||
                user.getUsername().equals("") ||
                user.getPassword() == null ||
                user.getPassword().equals("")) {
            // 返回错误信息
            request.setAttribute("msg", "请输入用户名或密码");
            return "login";
        }
        User exsitUser = userService.findUser(user);
        // 判断用户是否存在
        if (exsitUser != null) {
            // 设置session 存入信息
            HttpSession session = request.getSession();
            session.setAttribute(User.NAMESPACE, exsitUser.getUsername());
            session.setAttribute("totalSize", exsitUser.getTotalSize());
            return "redirect:/index.action";
        } else {
            // 返回错误信息
            request.setAttribute("msg", "用户名或密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        // 清空session
        request.getSession().invalidate();
        // 返回登录页
        return "redirect:/user/login.action";
    }

    @RequestMapping("/regist")
    public String regist(HttpServletRequest request, HttpServletResponse response, User user) {
        // 判断输入是否合法
        if (user.getUsername() == null || user.getPassword() == null || user.getUsername().equals("") || user.getPassword().equals("")) {
            request.setAttribute("msg", "请输入用户名和密码");
            return "regist";
        } else {
            boolean flag = userService.addUser(user);
            if (flag) {
                // 创建对应文件夹，跳转到登录界面
                fileService.addNewNameSpace(request, user.getUsername());
                return "login";
            } else {
                 // 返回错误信息
                request.setAttribute("msg", "注册失败");
                return "regist";
            }
        }
    }
}
